package com.springboot.controller.web;

import com.springboot.mapper.DoctorAppointSetMapper;
import com.springboot.model.DoctorAppointSet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class DownloadExcelController {
    @Autowired
    DoctorAppointSetMapper doctorAppointSetMapper;

    private static final long serialVersionUID = 1L;
    // 确认当前系统属性。获取当前系统属性。系统文件分割
    public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");

    @CrossOrigin
    @RequestMapping(value = "/webdownloadexcel")
    @ResponseBody
    public void webDownloadExcel(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
        // 请求发送都是utf-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        Integer doctorId = (Integer)session.getAttribute("doctorId");
        // 查询用户信息
        System.out.println("EXCEL导出 医生ID："+doctorId);
        List<DoctorAppointSet> doctorAppointSets = new ArrayList<>();
        try {
//            doctorAppointSets = doctorAppointSetMapper.selectByDoctorId(doctorId);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("DownloadExcelController 出错");
        }

        // 本地年月日时分秒作为文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sdf.format(new Date()) + ".xlsx";
        // 文件路径
        String filePath = FILE_SEPARATOR + fileName;
        filePath = "E:\\桌面\\"+fileName;
        File file = new File(filePath);
        if(!file.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            file.getParentFile().mkdir();
            try {
                //创建文件
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // 输出流
            OutputStream os = new FileOutputStream(filePath);
            // 工作区
            XSSFWorkbook wb = new XSSFWorkbook();
            // 工作区名
            XSSFSheet sheet = wb.createSheet("排班表");

            // 创建表头
            XSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("医生编号");
            row.createCell(1).setCellValue("预约日期");
            row.createCell(2).setCellValue("上午预约人数");
            row.createCell(3).setCellValue("下午预约人数");
            // 遍历数据装进table
            SimpleDateFormat sdf1 = new SimpleDateFormat("YYYY-mm-dd");
            for (int i = 0; i < doctorAppointSets.size(); i++) {
                // sheet.createRow(i+1) 因为表头是0
                XSSFRow rows = sheet.createRow(i + 1);
                String bookDate = sdf1.format(doctorAppointSets.get(i).getBookDate());
                rows.createCell(0).setCellValue(doctorAppointSets.get(i).getDoctorId());
                rows.createCell(1).setCellValue(bookDate);
                rows.createCell(2).setCellValue(doctorAppointSets.get(i).getMorningNum());
                rows.createCell(3).setCellValue(doctorAppointSets.get(i).getAfternoonNum());
            }

            wb.write(os);
            // 关闭输出流
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("准备执行下载啦");
        download(filePath, response);
    }

    private void download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
